package cn.wildfire.chat.kit.user;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.google.gson.Gson;
import com.lqr.imagepicker.ImagePicker;
import com.lqr.imagepicker.bean.ImageItem;
import com.sourcemuch.im.caiba.R;import com.sourcemuch.im.caiba.R2;
import com.sourcemuch.im.caiba.R2;

import java.util.ArrayList;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.Observer;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.wildfire.chat.app.extendsion.widgets.CircleImageView;
import cn.wildfire.chat.kit.WfcScheme;
import cn.wildfire.chat.kit.WfcUIKit;
import cn.wildfire.chat.kit.common.OperateResult;
import cn.wildfire.chat.kit.qrcode.QRCodeActivity;
import cn.wildfire.chat.kit.third.utils.ImageUtils;
import cn.wildfirechat.model.UserInfo;
import cn.wildfirechat.model.UserInfoExtra;

/**
 * @Author LiZhong
 * @Date 2019/9/7
 */
public class PersonalInfoFragment extends Fragment {


    @BindView(R2.id.cv_head)
    CircleImageView cvHead;
    @BindView(R2.id.tv_nick_name)
    TextView tvNickName;
    @BindView(R2.id.tv_account)
    TextView tvAccount;
    @BindView(R2.id.tv_date)
    TextView tvDate;
    @BindView(R2.id.rl_caiba_account)
    RelativeLayout rlCaibaAccount;
    @BindView(R2.id.tv_phone)
    TextView tvPhone;
    @BindView(R2.id.tv_signature)
    TextView tvSignature;

    private UserInfo userInfo;
    private UserViewModel userViewModel;
    private String portrait;

    public static PersonalInfoFragment newInstance(UserInfo userInfo) {
        PersonalInfoFragment fragment = new PersonalInfoFragment();
        Bundle args = new Bundle();
        args.putParcelable("userInfo", userInfo);
        fragment.setArguments(args);
        return fragment;
    }

    /**
     * modify by HEKE , 2019/8/23 18:37
     * TODO 交友设置外部传入参数
     */
    int privateChat;
    boolean requestIsManager;
    boolean isFromGroupSet;

    /**
     * 绑定交友设置参数
     *
     * @param privateChat
     * @param requestIsManager
     */
    public void setPrivateChatAttrs(int privateChat, boolean requestIsManager) {
        this.privateChat = privateChat;
        this.requestIsManager = requestIsManager;
        this.isFromGroupSet = true;
    }

    private Observer<List<UserInfo>> userInfoLiveDataObserver = new Observer<List<UserInfo>>() {
        @Override
        public void onChanged(@Nullable List<UserInfo> userInfos) {
            if (userInfos == null) {
                return;
            }
            for (UserInfo info : userInfos) {
                if (info.uid.equals(userViewModel.getUserId())) {
                    userInfo = info;
                    if (userInfo != null) {
                        setUserInfo(userInfo);
                    }
                    break;
                }
            }
        }
    };

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_modify_personal_info, container, false);
        ButterKnife.bind(this, view);
        init();
        return view;
    }

    @Override
    public void onResume() {
        super.onResume();

        UserInfo userInfo = null;
        userInfo = new UserViewModel().getUserInfo(userViewModel.getUserId(), true);
        if (userInfo != null) {
            setUserInfo(userInfo);
            portrait = userInfo.portrait;
        }
    }

    public void init() {
        Bundle args = getArguments();
        assert args != null;
        userInfo = args.getParcelable("userInfo");

        userViewModel = WfcUIKit.getAppScopeViewModel(UserViewModel.class);
        if (userInfo != null) {
            setUserInfo(userInfo);
        }

        userViewModel.userInfoLiveData().observe(this, userInfos -> {
            for (UserInfo info : userInfos) {
                if (userInfo.uid.equals(info.uid)) {
                    userInfo = info;
                    setUserInfo(info);
                    break;
                }
            }
        });
        UserInfo userInfo = null;
        userInfo = new UserViewModel().getUserInfo(userViewModel.getUserId(), true);
        if (userInfo != null) {
            setUserInfo(userInfo);
        }
        userViewModel.userInfoLiveData().observeForever(userInfoLiveDataObserver);
        portrait = userInfo.portrait;
    }

    private void setUserInfo(UserInfo userInfo) {
        //设置头像
        if (getContext() != null) {
            Glide.with(getContext()).load(userInfo.portrait).apply(new RequestOptions().
                    placeholder(R.mipmap.avatar_def).centerCrop()).into(cvHead);
        }
        //设置昵称
        tvNickName.setText(userInfo.displayName);

        Gson gson = new Gson();
        UserInfoExtra userInfoExtra = gson.fromJson(userInfo.extra, UserInfoExtra.class);
        if (userInfoExtra != null) {
            if ("1".equals(userInfoExtra.getIs_edit())) {
                rlCaibaAccount.setOnClickListener(null);
                rlCaibaAccount.findViewById(R.id.iv_account_arrow).setVisibility(View.GONE);
            }
            //设置信推号
            tvAccount.setText(userInfoExtra.getCaiba_number());
            //设置注册时间
            tvDate.setText(userInfoExtra.getCreate_time().substring(0, userInfoExtra.getCreate_time().indexOf(" ")));
            // 设置手机号
            tvPhone.setText("" + userInfo.mobile);
            //设置个性签名
            tvSignature.setText(userInfo.social);
        }
    }

    @OnClick({R2.id.rl_modify_head, R2.id.rl_modify_nick_name, R2.id.rl_qr_code, R2.id.rl_caiba_account, R2.id.rl_modify_signature})
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.rl_modify_head) {
            Intent intentModifyHead = new Intent(getContext(), ChangeHeadActivity.class);
            if (portrait != null && !portrait.equals("")) {
                intentModifyHead.putExtra("portrait", portrait);
            }
            startActivity(intentModifyHead);
        } else if (id == R.id.rl_modify_nick_name) {
            Intent intent = new Intent(getContext(), ChangeNameActivity.class);
            startActivity(intent);
        } else if (id == R.id.rl_qr_code) {
            UserInfo userInfo = userViewModel.getUserInfo(userViewModel.getUserId(), false);
            String qrCodeValue = WfcScheme.QR_CODE_PREFIX_USER + userInfo.uid;
            startActivity(QRCodeActivity.buildQRCodeIntent(getContext(), getString(R.string.qrcode_title2), userInfo.portrait, qrCodeValue, userInfo));
        } else if (id == R.id.rl_caiba_account) {
            Intent intentAccount = new Intent(getContext(), ChangeAccountActivity.class);
            startActivity(intentAccount);
        } else if (id == R.id.rl_modify_signature) {
            Intent intentSocial = new Intent(getContext(), ChangeSignatureActivity.class);
            startActivity(intentSocial);
        }
    }

    private static final int REQUEST_CODE_PICK_IMAGE = 100;

    private void updatePortrait() {
        ImagePicker.picker().pick(this, REQUEST_CODE_PICK_IMAGE);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_CODE_PICK_IMAGE && resultCode == Activity.RESULT_OK) {
            ArrayList<ImageItem> images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
            String imagePath = ImageUtils.genThumbImgFile(images.get(0).path).getAbsolutePath();
            MutableLiveData<OperateResult<Boolean>> result = userViewModel.updateUserPortrait(imagePath);
            result.observe(this, booleanOperateResult -> {
                if (booleanOperateResult.isSuccess()) {
                    Toast.makeText(getContext(), getString(R.string.update_head_success), Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(getContext(), getString(R.string.update_head_failure) + ": " + booleanOperateResult.getErrorCode(), Toast.LENGTH_SHORT).show();
                }
            });
        } else {
            super.onActivityResult(requestCode, resultCode, data);
        }
    }


}
